package com.gdth.bank.widget.baiduMap;

import java.io.File;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.LocationClientOption.LocationMode;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.VersionInfo;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMapDoubleClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMapLoadedCallback;
import com.baidu.mapapi.map.BaiduMap.OnMapLongClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerClickListener;
import com.baidu.mapapi.map.BaiduMap.OnMarkerDragListener;
import com.baidu.mapapi.map.BaiduMap.OnMyLocationClickListener;
import com.baidu.mapapi.map.BaiduMap.SnapshotReadyCallback;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.InfoWindow;
import com.baidu.mapapi.map.MapPoi;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.map.PolygonOptions;
import com.baidu.mapapi.map.Stroke;
import com.baidu.mapapi.map.offline.MKOLSearchRecord;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.RouteLine;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.route.DrivingRouteLine;
import com.baidu.mapapi.search.route.DrivingRoutePlanOption;
import com.baidu.mapapi.search.route.PlanNode;
import com.baidu.mapapi.search.route.RoutePlanSearch;
import com.baidu.mapapi.search.route.TransitRouteLine;
import com.baidu.mapapi.search.route.TransitRoutePlanOption;
import com.baidu.mapapi.search.route.WalkingRouteLine;
import com.baidu.mapapi.search.route.WalkingRoutePlanOption;
import com.gdth.animation.AnimationUtil;
import com.gdth.animation.AnimationUtil.AnimationType;
import com.gdth.bank.BankApplication;
import com.gdth.bank.R;
import com.gdth.bank.widget.baiduMap.BBDLocationListener.LocatonSeleted;
import com.gdth.bank.widget.baiduMap.BOnGetGeoCoderResultListener.GeoCoderCallBack;
import com.gdth.bank.widget.baiduMap.BOnGetRoutePlanResultListener.RouteCallBack;
import com.gdth.core.widget.BaseActivity;
import com.gdth.widget.dialog.BaseToast;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class BaseMapActivity extends BaseActivity implements OnClickListener, LocatonSeleted {
	
	/**
	 * 地图类型窗体弹出按钮
	 */
	private TextView btn_model;
	
	/**
	 * 地图类型选择按钮
	 */
	private TextView btn_model_normal, btn_model_satellite, btn_model_3d;
	
	/**
	 * 地图类型窗体
	 */
	private LinearLayout linear_map_layer, linear_map_model;
	
	/**
	 * 地图控件
	 */
	protected MapView mapView = null; 
	
	/**
	 * 坐标数组，用于画多边形
	 */
	protected List<LatLng> latlngList = new ArrayList<LatLng>();
	
	protected boolean isDian = false, isXian = false;

	public static List<Activity> activityList = new LinkedList<Activity>();
	
	/*****************定位资源*****************/
	/**
	 * 定位按钮
	 */
	protected TextView btn_location;

	/**
	 * 定位模式图片 
	 */
	private BitmapDescriptor img_market, img_location_follow, img_location_compass;

	/**
	 * 定位核心
	 */
	public LocationClient mLocationClient;

	/**
	 * 定位监听
	 */
	private BBDLocationListener mBBDLocationListener;
	
	/**
	 * 定位点的坐标
	 */
	protected LatLng locationLatLng;
	
	protected boolean isFirstLocate = true, isLocate = false;
	
	/**
	 * 定位模式标识
	 */
	protected int location_model = location_model_tp;

	private static final int location_model_tp = 101;
	private static final int location_model_normal = 102;
	private static final int location_model_compass = 103;
	private static final int location_model_follow = 104;
	
	public static final String APP_FOLDER_NAME = "BNSDKSimpleDemo";

	public static final String ROUTE_PLAN_NODE = "routePlanNode";
	public static final String SHOW_CUSTOM_ITEM = "showCustomItem";
	public static final String RESET_END_NODE = "resetEndNode";
	public static final String VOID_MODE = "voidMode";
	double LatitudeJd;
	double LongitudeWd;
	
	
	/*****************漂浮窗体资源*****************/
	/**
	 * 漂浮窗体
	 */
	protected LinearLayout linear_infowindow;
	
	/**
	 * 漂浮窗体标题、内容
	 */
	protected TextView txt_infowindow_title, txt_infowindow_content;
	
	
	/********************地图资源*********************/
	/**
	 * 百度地图
	 */
	protected BaiduMap baiduMap = null;
	
	private int mapId = R.id.bmapView;
	
	
	protected List<String> addressList = new ArrayList<String>();

	
	
	/*********************信息搜索*********************/
	/**
	 * 地图信息搜索模块
	 */
	private GeoCoder mSearch = null;

	
	/*********************交通线路资源*********************/
	/**
	 * 交通线路搜索模块
	 * 可去掉地图模块独立使用
	 */
	RoutePlanSearch mRoutePlanSearch = null;
	
	/**
	 * 交通线路搜索结果集
	 */
	RouteLine<?> route = null;
	
	/**
	 * 交通线路点覆盖物
	 */
	OverlayManager mOverlayManager = null;
	
	/**
	 * 交通线路搜索结果集索引
	 */
	private int nodeIndex = -1;
	
	/**
	 * 交通线路点显示载体
	 */
	private TextView popupText = null;
	
	/**
	 * 线路点跳转按钮
	 */
	protected TextView btn_unit_dian, btn_unit_edit;
	
	String authinfo = null;
	
	private SDKReceiver mReceiver;
	public boolean isOpen = false;
	
	public class SDKReceiver extends BroadcastReceiver {
		public void onReceive(Context context, Intent intent) {
			String s = intent.getAction();
	
			if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR)) {
				BaseToast.getInstance().ShowCenterToast(BaseMapActivity.this, "key 验证出错! 请在 AndroidManifest.xml 文件中检查 key 设置");
			} else if (s.equals(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK)) {
//				BaseToast.getInstance().ShowCenterToast(BaseMapActivity.this, "key 验证成功! 功能可以正常使用");
			}
			else if (s.equals(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR)) {
				BaseToast.getInstance().ShowCenterToast(BaseMapActivity.this, "网络出错");
			}
		}
	}
	
	/**
	 * 构造函数
	 * @param
	 */
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
//		setContentView(R.layout.activity_main);
        
    }
	
    /**
     * 初始化界面
     */
	protected void init() {
//		BaseToast.getInstance().ShowCenterToast(BaseMapActivity.this, "欢迎使用百度地图Android SDK v" + VersionInfo.getApiVersion());
		
		// 注册 SDK 广播监听者
		IntentFilter iFilter = new IntentFilter();
		iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_OK);
		iFilter.addAction(SDKInitializer.SDK_BROADTCAST_ACTION_STRING_PERMISSION_CHECK_ERROR);
		iFilter.addAction(SDKInitializer.SDK_BROADCAST_ACTION_STRING_NETWORK_ERROR);
		mReceiver = new SDKReceiver();
		registerReceiver(mReceiver, iFilter);
		
		activityList.add(this);
		
		//初始化数据
		initData();
		
		initView();
    	
    	//初始化地图
    	initMap();
    	
    	//初始化定位
		InitLocation();
    	
		//获取中心点
//    	baiduMap.getMapStatus().target;
    	
    	//初始化搜索模块，注册事件监听
		mSearch = GeoCoder.newInstance();
		BOnGetGeoCoderResultListener mBOnGetGeoCoderResultListener = new BOnGetGeoCoderResultListener();
		mBOnGetGeoCoderResultListener.setGeoCoderCallBack(mGeoCoderCallBack);
		mSearch.setOnGetGeoCodeResultListener(mBOnGetGeoCoderResultListener);
		
		//初始化搜索模块，注册事件监听
    	mRoutePlanSearch = RoutePlanSearch.newInstance();
    	
    	BOnGetRoutePlanResultListener mBOnGetRoutePlanResultListener = new BOnGetRoutePlanResultListener(useDefaultIcon, baiduMap);
    	mBOnGetRoutePlanResultListener.setRouteCallBack(mRouteCallBack);
    	mRoutePlanSearch.setOnGetRoutePlanResultListener(mBOnGetRoutePlanResultListener);
	}
	
	/**
	 * 初始化数据
	 */
	private void initData(){
    	//定位指示图片
    	img_location_compass = BitmapDescriptorFactory.fromResource(R.drawable.map_icon_location_compass);
    	img_location_follow = BitmapDescriptorFactory.fromResource(R.drawable.map_icon_location_follow);
 		img_market = BitmapDescriptorFactory.fromResource(R.drawable.map_market);
	}
	
	/**
	 * 初始化界面
	 */
	private void initView(){
        //地图控件
        mapView = (MapView) findViewById(mapId); 
		
    	//地图类型窗体
    	linear_map_model = (LinearLayout) findViewById(R.id.baidu_linear_model);
    	linear_map_layer = (LinearLayout) findViewById(R.id.baidu_linear_model_layer);
    	
        //地图类型弹出按钮
        btn_model = (TextView) findViewById(R.id.baidu_btn_model);
    	btn_model.setOnClickListener(this);
    	//地图类型选择按钮
        btn_model_normal = (TextView) findViewById(R.id.baidu_btn_model_plain);
        btn_model_satellite = (TextView) findViewById(R.id.baidu_btn_model_satellite);
        btn_model_3d = (TextView) findViewById(R.id.baidu_btn_model_3d);
		btn_model_normal.setOnClickListener(this);
		btn_model_satellite.setOnClickListener(this);
    	btn_model_3d.setOnClickListener(this);
        
        //定位按钮
		btn_location = (TextView) findViewById(R.id.baidu_btn_loaction);
    	btn_location.setOnClickListener(this);
    	
    	//漂浮窗体
    	linear_infowindow = (LinearLayout) findViewById(R.id.baidu_map_infowindow);
    	txt_infowindow_title = (TextView) findViewById(R.id.baidu_map_infowindow_title);
    	txt_infowindow_content = (TextView) findViewById(R.id.baidu_map_infowindow_content);
    	
    	btn_unit_dian = (TextView) findViewById(R.id.map_btn_unit_dian);
    	btn_unit_edit = (TextView) findViewById(R.id.map_btn_unit_edit);
    	btn_unit_dian.setBackgroundResource(R.drawable.map_button_corner_left);
		btn_unit_edit.setBackgroundResource(R.drawable.map_button_corner_right);

    	btn_unit_dian.setOnClickListener(this);
    	btn_unit_edit.setOnClickListener(this);
	}
	
	/**
	 * 初始化地图
	 */
	private void initMap(){
    	baiduMap = mapView.getMap();

		// 设置百度地图的一些状态放大16等级
    	baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder(baiduMap.getMapStatus()).zoom(16).build())); 
    	
    	//地图监听事件
    	baiduMap.setOnMapClickListener(onMapClickListener);
    	baiduMap.setOnMapLongClickListener(onMapLongClickListener);
    	baiduMap.setOnMapDoubleClickListener(onMapDoubleClickListener);
    	
    	baiduMap.setOnMarkerClickListener(onMarkerClickListener);
    	baiduMap.setOnMapStatusChangeListener(onMapStatusChangeListener);
    	baiduMap.setOnMarkerDragListener(nMarkerDragListener);
	}
	
	/**
	 * 初始化定位
	 */
	protected void InitLocation(){
		//设置定位图层
    	baiduMap.setMyLocationEnabled(true);
    	
		//初始化LocationClient
		mLocationClient = new LocationClient(this.getApplicationContext());
		
		//定位监听
		mBBDLocationListener = new BBDLocationListener(baiduMap, onMyLocationClickListener);
		mBBDLocationListener.setLocatonSeleted(this);
		//注册
 		mLocationClient.registerLocationListener(mBBDLocationListener);
 		
		LocationClientOption option = new LocationClientOption();
		option.setLocationMode(LocationMode.Hight_Accuracy);	//LocationMode.Hight_Accuracy, LocationMode.Battery_Saving, LocationMode.Device_Sensors
		option.setCoorType("bd09ll");							//gcj02(国测密经纬度坐标), bd09ll(百度加密经纬度坐标), bd09(百度加密墨卡托坐标)
		option.setOpenGps(true); 								// 打开GPS
    	option.setTimeOut(10 * 1000); 							// 超时
		option.setScanSpan(1000);								//定位时间间隔
		option.setIsNeedAddress(true);							//反地理编		
		option.setNeedDeviceDirect(true);						// 返回的定位结果包含手机机头的方向
//		option.setIsNeedLocationPoiList(true);					
		option.setIsNeedLocationDescribe(true);					// 模糊定位
		option.setLocationNotify(true);
		
		mLocationClient.setLocOption(option);
	}
	public String realAddress = "";
	public double realLatitude = 0;
	public double realLongitude = 0;
	public LocationBean getLocationAddress(){
		if (mBBDLocationListener.mBDLocation.hasAddr()){
			LocationBean bean = new LocationBean();
			String address = mBBDLocationListener.mBDLocation.getAddrStr();
			
				double jd = mBBDLocationListener.mBDLocation.getLatitude();
				double wd = mBBDLocationListener.mBDLocation.getLongitude();
				bean.setAddress(address);
				bean.setJd(jd);
				bean.setWd(wd);
			return bean;
		}else if(0 != realLatitude && 0 !=  realLongitude){
			LocationBean bean = new LocationBean();
			bean.setAddress(realAddress);
			bean.setJd(realLatitude);
			bean.setWd(realLongitude);
			return bean;
		}
		return null;
		
	}
	
	@Override
	public void onClick(View arg0) {
		// TODO Auto-generated method stub
		int id = arg0.getId();
		
		if (id == R.id.baidu_btn_model)
			showLinearLayer();
		
		if (id == R.id.baidu_btn_model_plain)
			ChangeMapType(BaiduMap.MAP_TYPE_NORMAL);

		if (id == R.id.baidu_btn_model_3d)
			ChangeMapType(BaiduMap.MAP_TYPE_NORMAL);

		if (id == R.id.baidu_btn_model_satellite)
			ChangeMapType(BaiduMap.MAP_TYPE_SATELLITE);
		
		if (id == R.id.baidu_btn_loaction)
			StartLocation();
		
		if (id == R.id.map_btn_unit_dian)
				selectNode(arg0);
		if (id == R.id.map_btn_unit_edit)
				selectNode(arg0);
	}
	
	/**
	 * 显示或隐藏地图类型窗体
	 */
	private void showLinearLayer(){
		if (linear_map_layer.getVisibility() == View.GONE) {
			linear_map_model.setBackgroundResource(R.drawable.map_locatebtn_up);
			btn_model.setBackgroundResource(R.drawable.map_model_icon_close);
			AnimationUtil.ScaleOut(linear_map_layer, AnimationType.scaleTopRightOut, 500);
		} else {
			linear_map_model.setBackgroundResource(R.drawable.map_locatebtn_down);
			btn_model.setBackgroundResource(R.drawable.map_model_icon_maplayers);
			AnimationUtil.ScaleIn(linear_map_layer, AnimationType.scaleTopRightIn, 500);
		}
	}

	
	/**
	 * 改变地图资源
	 * @param type
	 */
	private void ChangeMapType(int type){	
		baiduMap.setMapType(type);  
	}


	
	/***************************定位事件***************************/
	/**
	 * 启动定位
	 */
	public void StartLocation(){
		switch(location_model){
			case location_model_tp:
				btn_location.setBackgroundResource(R.drawable.map_icon_location_compass);
		    	baiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
		    			MyLocationConfiguration.LocationMode.COMPASS, true, img_location_compass));
		    	
		    	break;
			case location_model_compass:
				btn_location.setBackgroundResource(R.drawable.map_icon_location_follow);
				baiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
	    			MyLocationConfiguration.LocationMode.FOLLOWING, true, img_location_follow));
				break;
			case location_model_follow:
				btn_location.setBackgroundResource(R.drawable.map_icon_location_normal);
		    	baiduMap.setMyLocationConfigeration(new MyLocationConfiguration(
		    			MyLocationConfiguration.LocationMode.NORMAL, true, img_location_compass));
		    	break;
			case location_model_normal:
				btn_location.setBackgroundResource(R.drawable.map_icon_location);
				break;
		}
		
		if (location_model != 4){
			mLocationClient.start();
			isLocate = true;
		}
	}
    
	/**
	 * 停止定位
	 */
	protected void StopLocation(){
		// TODO 停止定位
		if (mLocationClient != null)
			mLocationClient.stop();
		isLocate = false;
		location_model = 1;
	}
	
    /**
     * 地图定位图标点击事件监听接口
     */
    OnMyLocationClickListener onMyLocationClickListener = new OnMyLocationClickListener(){
		@Override
		public boolean onMyLocationClick() {
			//存在定位地址，弹出
			if (mBBDLocationListener.mBDLocation.hasAddr())
				showInfoWindow(mBBDLocationListener.mBDLocation.getAddrStr());
			
			return false;
			
		}
	};
	
	
	/*************************覆盖物************************/
	/**
	 * 添加覆盖物
	 * @param point
	 */
	public void addMarker(LatLng point){
		OverlayOptions ooA = new MarkerOptions().position(point).icon(img_market).zIndex(9).draggable(true);
		baiduMap.addOverlay(ooA);
		
		if (isDian){
			searchGeoCode(point);
		}
		
		// 第一次进入百度地图
		//if (isFirstLocate) {
//			isFirstLocate = false;
//			// 移动到我的位置，默认动画效果时间300ms
//			baiduMap.animateMapStatus(MapStatusUpdateFactory.newLatLng(point), 600);
//		}
		
		// 基于原来的status上改变指定的参数
//		MapStatus mapStatus = new MapStatus.Builder(baiduMap.getMapStatus()).target(point).build();
//		MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.newMapStatus(mapStatus);
//		baiduMap.animateMapStatus(mapStatusUpdate); // 改变,这里设置成改变位置
	}
	
	 /**
     *  地图 Marker 覆盖物点击事件监听接口：
     */
    OnMarkerClickListener onMarkerClickListener = new OnMarkerClickListener() {
		@Override
		public boolean onMarkerClick(Marker arg0) {
			// TODO Auto-generated method stub

			searchGeoCode(arg0.getPosition());
			return false;
		}
    };
	
    /**
     * 覆盖物拖伐事件
     */
    OnMarkerDragListener nMarkerDragListener = new OnMarkerDragListener() {
        public void onMarkerDrag(Marker marker) {
            //拖拽
        }
        public void onMarkerDragEnd(Marker marker) {
        	if (isXian){
	            //拖拽结束
	        	if (latlngList.size() > 2){
					
					baiduMap.clear();
					for (LatLng lat : latlngList){
						addMarker(lat);
					}
					
					OverlayOptions ooPolygon = new PolygonOptions().points(latlngList)
							.stroke(new Stroke(5, 0xAA00FF00)).fillColor(0xAAFFFF00);
					
					baiduMap.addOverlay(ooPolygon);
				}
        	}
        }
        public void onMarkerDragStart(Marker marker) {
            //拖拽
        }
    };
    
	/*************************漂浮窗口************************/
	/**
	 * 现实漂浮窗口
	 * @param position
	 * @param
	 */
	protected void showInfoWindow(String position) {
		// TODO 打开漂浮窗
		linear_infowindow.setVisibility(View.VISIBLE);
		txt_infowindow_content.setText(position);
	}
	
	
	/******************Activity接口事件***************/
 	public void onStopLocation() {
		// TODO 停止导航事件
		mLocationClient.stop();
	}
 	public void onDestroyMap() {
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管
        // 退出时销毁
        if (mLocationClient != null)
        	mLocationClient.stop();
        
 		// 关闭定位图层
 		baiduMap.setMyLocationEnabled(false);
 		mapView.onDestroy();
 		mapView = null;
 		img_market.recycle();
 		
    	unregisterReceiver(mReceiver);
    }  
      
 	public void onResumeMap() {   
        //在activity执行onResume时执行mMapView. onResume()，实现地图生命周期管�? 
        mapView.onResume();  
    } 
    
 	public void onPauseMap() { 
        //在activity执行onPause时执行mMapView. onPause()，实现地图生命周期管�? 
        mapView.onPause();  
    }
	
    
    /******************map监听事件***************/
    /**
     * 地图状态事件
     */
    OnMapStatusChangeListener onMapStatusChangeListener = new OnMapStatusChangeListener() {


        @Override
        public void onMapStatusChangeStart(MapStatus mapStatus) {

        }

        /**
         * 手势操作地图，设置地图状态等操作
         * @param
         */
        @Override
		public void onMapStatusChangeStart(MapStatus mapStatus, int i) {

		}

		/**
        * 地图状变化
        * @param status 当前地图
        */  
        public void onMapStatusChange(MapStatus status){
        	
        }  
        
        /** 
        * 地图状态改变结束 
        * @param status 地图状态改变结束后的地图状态 
        */  
        public void onMapStatusChangeFinish(MapStatus status){
        }  
    };
    
    /**
     * 地图单击事件监听接口
     */
    OnMapClickListener onMapClickListener = new OnMapClickListener() {
		@Override
		public void onMapClick(LatLng arg0) {
			// TODO Auto-generated method stub
			if (linear_infowindow.getVisibility() != View.GONE) {
				linear_infowindow.setVisibility(View.GONE);
				return;
			}
			if (location_model == 2 || location_model == 3){
				StopLocation();
				btn_location.setBackgroundResource(R.drawable.map_icon_location);
				location_model = 1;
			}
			
			if (isDian) {
				baiduMap.clear();
				addMarker(arg0);
			}
			if (isXian){
				addMarker(arg0);
				latlngList.add(arg0);
				
				if (latlngList.size() > 2){
					
					baiduMap.clear();
					for (LatLng lat : latlngList){
						addMarker(lat);
					}
					
					OverlayOptions ooPolygon = new PolygonOptions().points(latlngList)
							.stroke(new Stroke(5, 0xAA00FF00)).fillColor(0xAAFFFF00);
					
					baiduMap.addOverlay(ooPolygon);
				}
			}
		}

		@Override
		public boolean onMapPoiClick(MapPoi arg0) {
			// TODO Auto-generated method stub
			return false;
		}
    };

    /**
     * 地图长按事件监听接口
    */
    OnMapLongClickListener onMapLongClickListener = new OnMapLongClickListener() {    
        public void onMapLongClick(LatLng point){
        	
        }  
    };
    
    /**
     * 地图双击事件监听接口
     */
    OnMapDoubleClickListener onMapDoubleClickListener = new OnMapDoubleClickListener() {  
        public void onMapDoubleClick(LatLng point){  
        	if (isXian){
	        	if (latlngList.size() > 0){
	        		mapView.getMap().clear();
	        		latlngList.clear();
	        		
	        		return;
	        	}
        	}
        }  
    };
    
    /**
     * 地图加载完成回调接口
     */
    OnMapLoadedCallback onMaoLoadedCallback = new OnMapLoadedCallback() {  
        public void onMapLoaded(){
        }  
    };
    
	/** 
	 * 地图截屏回调接口
	 */
	SnapshotReadyCallback snapshotReadyCallback = new SnapshotReadyCallback() {  
	    public void onSnapshotReady(Bitmap snapshot){  
	    }  
	};
	
	
	
	
	/*******************Geo搜索事件*********************/
	/**
	 * 反Geo搜索
	 */
	protected void searchGeoCode(LatLng latlng){
		mSearch.reverseGeoCode(new ReverseGeoCodeOption().location(latlng));
	}

	GeoCoderCallBack mGeoCoderCallBack = new GeoCoderCallBack(){

		@Override
		public void updateView(ReverseGeoCodeResult arg0) {
			// TODO Auto-generated method stub
			showInfoWindow(arg0.getAddress());
		}

		@Override
		public void showError(String msg) {
			// TODO Auto-generated method stub
			showToastMsg(msg);
		}};
	
	/********************线路查询事件*******************/
	boolean useDefaultIcon = false;

    
    RouteCallBack mRouteCallBack = new RouteCallBack(){

		@Override
		public void updateView(OverlayManager mOverlayManager, RouteLine<?> route) {
			// TODO Auto-generated method stub
			nodeIndex = -1;
            btn_unit_dian.setVisibility(View.VISIBLE);
            btn_unit_edit.setVisibility(View.VISIBLE);
      
            baiduMap.setOnMarkerClickListener(mOverlayManager);

		}
    	
		@Override
		public void showError(String msg){
			showToastMsg(msg);
		}
    };
    
//	/**
//	 * 线路查询
//	 * @param sCity
//	 * @param eCity
//	 * @param sAddress
//	 * @param eAddress
//	 */
//	public void RoutePlanOption(String sCity, String eCity, String sAddress, String eAddress, int type){
//		// TODO Auto-generated method stub
//		//重置浏览节点的路线数据
//        route = null;
//        btn_unit_dian.setVisibility(View.INVISIBLE);
//        btn_unit_edit.setVisibility(View.INVISIBLE);
//        baiduMap.clear();
//        
//        //设置起终点信息，对于tranist search 来说，城市名无意义
//        PlanNode sNode = PlanNode.withCityNameAndPlaceName(sCity, sAddress);
//        PlanNode eNode = PlanNode.withCityNameAndPlaceName(eCity, eAddress);
//        
//
//        // 实际使用中请对起点终点城市进行正确的设定
//        switch(type){
//	        case 1:
//	        	mRoutePlanSearch.drivingSearch((new DrivingRoutePlanOption())
//	        			.from(sNode)
//	                    .to(eNode));
//	            break;
//	        case 2:
//	        	mRoutePlanSearch.transitSearch((new TransitRoutePlanOption())
//	                    .from(sNode)
//	                    .city(sCity)
//	                    .to(eNode));
//            	break;
//	        case 3:
//	        	mRoutePlanSearch.walkingSearch((new WalkingRoutePlanOption())
//	                    .from(sNode)
//	                    .to(eNode));
//	            break;
//        }
//	}
	/**
	 * 线路查询
	 * @param sCity
	 * @param eCity
	 * @param
	 * @param
	 * cyx
	 */
	public void RoutePlanOption(String sCity, String eCity, LatLng point1, LatLng point, int type){
		// TODO Auto-generated method stub
		//重置浏览节点的路线数据
        route = null;
        btn_unit_dian.setVisibility(View.INVISIBLE);
        btn_unit_edit.setVisibility(View.INVISIBLE);
        baiduMap.clear();
        
        //设置起终点信息，对于tranist search 来说，城市名无意义
//        PlanNode sNode = PlanNode.withCityNameAndPlaceName(sCity, sAddress);
//        PlanNode eNode = PlanNode.withCityNameAndPlaceName(eCity, eAddress);
        
        PlanNode sNode = PlanNode.withLocation(new LatLng(point1.latitude, point1.longitude));
        PlanNode eNode = PlanNode.withLocation(new LatLng(point.latitude, point.longitude));

        // 实际使用中请对起点终点城市进行正确的设定
        switch(type){
	        case 1:
	        	mRoutePlanSearch.drivingSearch((new DrivingRoutePlanOption())
	        			.from(sNode)
	                    .to(eNode));
	            break;
	        case 2:
	        	mRoutePlanSearch.transitSearch((new TransitRoutePlanOption())
	                    .from(sNode)
	                    .city(sCity)
	                    .to(eNode));
            	break;
	        case 3:
	        	mRoutePlanSearch.walkingSearch((new WalkingRoutePlanOption())
	                    .from(sNode)
	                    .to(eNode));
	            break;
        }
	}
	/**********************线路查看事件*********************/
	
	/**
	 * 交通线路点击查看
	 *
	 */
	private void selectNode(View arg0){
		if (route == null ||
                route.getAllStep() == null) {
            return;
        }
        if (nodeIndex == -1 && arg0.getId() == R.id.map_btn_unit_dian) {
        	return;
        }
        //设置节点索引
        if (arg0.getId() == R.id.map_btn_unit_edit) {
            if (nodeIndex < route.getAllStep().size() - 1) {
            	nodeIndex++;
            } else {
            	return;
            }
        } else if (arg0.getId() == R.id.map_btn_unit_dian) {
        	if (nodeIndex > 0) {
        		nodeIndex--;
        	} else {
            	return;
            }
        }
        //获取节结果信息
        LatLng nodeLocation = null;
        String nodeTitle = null;
        Object step = route.getAllStep().get(nodeIndex);
        if (step instanceof DrivingRouteLine.DrivingStep) {
            nodeLocation = ((DrivingRouteLine.DrivingStep) step).getEntrance().getLocation();
            nodeTitle = ((DrivingRouteLine.DrivingStep) step).getInstructions();
        } else if (step instanceof WalkingRouteLine.WalkingStep) {
            nodeLocation = ((WalkingRouteLine.WalkingStep) step).getEntrance().getLocation();
            nodeTitle = ((WalkingRouteLine.WalkingStep) step).getInstructions();
        } else if (step instanceof TransitRouteLine.TransitStep) {
            nodeLocation = ((TransitRouteLine.TransitStep) step).getEntrance().getLocation();
            nodeTitle = ((TransitRouteLine.TransitStep) step).getInstructions();
        }

        if (nodeLocation == null || nodeTitle == null) {
            return;
        }
        //移动节点至中心
        baiduMap.setMapStatus(MapStatusUpdateFactory.newLatLng(nodeLocation));
        //
        popupText = new TextView(this);
        popupText.setBackgroundResource(R.drawable.map_guide_popup);
        popupText.setTextColor(0xFF000000);
        popupText.setText(nodeTitle);
        baiduMap.showInfoWindow(new InfoWindow(popupText, nodeLocation, 0));
	}

	/**
	 * 定位监听
	 */
	@Override
	public void seletedLocaton(BDLocation mBDLocation) {
		// TODO Auto-generated method stub

//    	StopLocation();
    	
		locationLatLng = new LatLng(baiduMap.getLocationData().latitude, baiduMap.getLocationData().longitude);
		
		showInfoWindow(mBBDLocationListener.mBDLocation.getAddrStr());
	}
	
	public void showToastMsg(final String msg) {
		this.runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(BaseMapActivity.this, msg, Toast.LENGTH_SHORT).show();
            }
        });
	}
	

	public String mSDCardPath = null;
	
	/**
	 * 初始化路径
	 * @return
	 */
	public boolean initDirs() {
		mSDCardPath = getSdcardDir();
		if (mSDCardPath == null) {
			return false;
		}
		File f = new File(mSDCardPath, APP_FOLDER_NAME);
		if (!f.exists()) {
			try {
				f.mkdir();
			} catch (Exception e) {
				e.printStackTrace();
				return false;
			}
		}
		return true;
	}

	public String getSdcardDir() {
		if (Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)) {
			return Environment.getExternalStorageDirectory().toString();
		}
		return null;
	}
	
}